import logging
import json
import re
            
from voice_assistant.commands.time_command import get_current_time
from voice_assistant.commands.win_opt import execute_command
from voice_assistant.my_state import app_state  # 导入全局状态对象
from voice_assistant.ai.ollama_client import simple_generate
from voice_assistant.config_manager import config_manager
from voice_assistant.event_system import event_system, Events, EventNames
from voice_assistant.my_config import PROMPT_CMD
from voice_assistant.commands.CommandParser import CommandParser

logger = logging.getLogger("process_command")
parser = CommandParser()

def process_command(command_text):
    """处理识别到的指令"""
    logger.info(f"处理指令: {command_text}")
    # 非空判断
    if not command_text:
        return
    
    # 处理包含"时间"的指令
    if "时间" in command_text:
        response = get_current_time()
    # 处理包含"天气"的指令
    elif "天气" in command_text:
        # 通过事件系统异步发布天气指令事件
        event_system.publish_async(Events.COMMAND_RECOGNIZED, {
            "command": EventNames.WEATHER,
            "params": {}
        })
        response = ''
    # 处理包含"退出会议"或"结束会议"的指令
    elif "退出会议" in command_text or "结束会议" in command_text:
        # 使用事件系统在主线程中关闭会议记录
        event_system.publish_async(Events.MEETING_RECORD, {
            "command": EventNames.RECORD_EXIT,
            "params": {}
        })
        response = ''
    # 处理包含"会议记录"或"会议模式"的指令
    elif "会议记录" in command_text or "会议模式" in command_text:
        # 使用事件系统在主线程中启动会议记录
        event_system.publish_async(Events.MEETING_RECORD, {
            "command": EventNames.RECORD_CREATED,
            "params": {}
        })
        
        response = ''
    # 处理包含"退出"或"停止"的指令
    elif "退出" in command_text or "停止" in command_text:
        # 更新应用状态为等待唤醒
        app_state.waiting_for_wake = True
        # 设置录音状态为停止
        app_state.is_recording = False
        response = "已停止识别"
    else:
        try:
            # 使用AI解析指令
            # cmd = ai_generate(command_text)
            # 使用命令解析器解析指令
            cmd = parser.parse_command(command_text)
            logger.info(f"返回: {cmd}")
            response = execute_cmd(cmd)
        except Exception as e:
            logger.error(f"处理指令时出错: {str(e)}")
            import traceback
            logger.error(traceback.format_exc())
            response = "处理指令时出错"
    
    if(response):
        event_system.publish(Events.UI_NOTIFICATION, {
            "title": "指令执行",
            "message": response,
            "type": "info"
        })
    return response

#使用ai解析指令
def ai_generate(cont):
    try:
        prompt = PROMPT_CMD.format(cont=cont)
        response = simple_generate(prompt, 
                                 model=config_manager.get("ai.model"), 
                                 base_url=config_manager.get("ai.url"), 
                                 **config_manager.get("ai.params", {}))
    except Exception as e:
        response = f"发生错误: {str(e)}"
    finally:
        return response
    
def execute_cmd(cmd) -> str:
    """根据命令执行操作，支持字符串和字典输入"""
    try:
        cmd_data = _normalize_command_input(cmd)
        if cmd_data is None:
            return "无法理解指令"
        
        logger.info(f"处理命令数据: {cmd_data}")
        
        # 检查是否支持该命令
        if not cmd_data.get("supported", False):
            reason = cmd_data.get("reason", "未知原因")
            response = f"无法执行指令: {reason}"
            logger.info(response)
            return response
        
        # 验证必要字段
        required_fields = ["command", "target"]
        missing_fields = [field for field in required_fields 
                         if field not in cmd_data or not cmd_data[field]]
        
        if missing_fields:
            logger.error(f"缺少必要字段: {missing_fields}")
            return f"指令不完整，缺少{', '.join(missing_fields)}信息"
        
        # 执行命令
        if execute_command(cmd_data):
            response = "指令已执行"
            logger.info(f"命令执行成功: {cmd_data['command']} -> {cmd_data['target']}")
        else:
            response = "指令执行失败"
            logger.error(f"命令执行失败: {cmd_data}")
            
    except Exception as e:
        logger.error(f"execute_ai函数发生未预期异常: {e}")
        response = f"系统错误: {str(e)}"
    
    return response

def _normalize_command_input(cmd):
    """将各种输入格式标准化为命令字典"""
    if cmd is None:
        return None
        
    # 如果已经是字典，直接返回
    if isinstance(cmd, dict):
        return cmd
    
    # 如果是字符串，尝试解析
    if isinstance(cmd, str):
        # 先尝试直接解析为JSON
        if cmd.strip().startswith('{') and cmd.strip().endswith('}'):
            try:
                return json.loads(cmd)
            except json.JSONDecodeError:
                pass  # 继续尝试其他方法
        
        # 尝试提取JSON部分
        json_match = re.search(r'\{[\s\S]*?\}', cmd, re.DOTALL)
        if json_match:
            try:
                json_str = json_match.group(0)
                return json.loads(json_str)
            except json.JSONDecodeError:
                logger.error(f"无法解析JSON: {json_str}")
        
        # 如果都不行，尝试构建基本命令结构
        logger.warning(f"无法解析命令字符串，尝试构建默认结构: {cmd}")
        return {
            "command": "",
            "target": "", 
            "value": "",
            "supported": False,
            "reason": "无法解析指令格式"
        }
    
    # 不支持的类型
    logger.error(f"不支持的命令输入类型: {type(cmd)}")
    return None